package org.lxg.mybatis.springandmybaits;

import org.apache.ibatis.session.SqlSession;

import org.junit.jupiter.api.Test;
import org.lxg.common.pojo.User;
import org.lxg.mybatis.dao.UserDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringMybatisDemo {
    static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");

    @Test
    public void test1() {

        /* 得到 SqlSession 对象*/
        SqlSession sqlSession = (SqlSession) context.getBean("sqlSession");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("start", 0);
        map.put("size", 5);

        // 调用 Mapper映射文件里的方法
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> list = mapper.findAllUsers();
        List<User> list2 = sqlSession.selectList("org.lxg.mybatis.dao.UserDao.findAllUsers", map);

        for (User user : list) {
            System.out.println(user);
        }
    }

    /**
     *  @Transactional
     *  当使用该注解的方法的调用方 是spring 管理的bean 才有可能生效
     */

    @Transactional(rollbackFor = Exception.class)
    public void business1() {
        UserDao mapper = context.getBean(UserDao.class);
        User c = mapper.findUserById(1);
        User u = new User("2", "A");
        mapper.insertUser(u);
        int i = 1 / 0;
        User w = new User("3", "B");
        mapper.insertUser(w);

    }

    public static void main(String[] args) {
        SpringMybatisDemo c = context.getBean(SpringMybatisDemo.class);
        c.business1();

        /**
         *  Spring 整合 mybatis
         *         1 关键对象的创建交给 spring 控制 ： 连接池对象，SqlSessionFactory工厂类, SqlSession对象
         */


    }

}